package guitforl.builders

import guitforl.wrappers.TabWrapper
import org.eclipse.swt.SWT
import org.eclipse.swt.layout.{GridData, GridLayout, FillLayout}
import org.eclipse.swt.widgets._
import org.eclipse.swt.graphics.Color

import scala.xml.NodeSeq

/**
 * Form = /tab+/
 * Tab = /grid/
 * Grid = /item+/
 * Item = /grid?/
 */
object TabBuilder {


  /**temp */
  val fill = new FillLayout()

  /**temp */

  val AREA_MAX_SIZE = 20
  val rand = scala.util.Random

  def liitleDarkness(x: Int) = if (x > 100) x - 100 else x

  def toNewMetric(oldValue: Int, maxValue: Int): Int = math.round(oldValue * maxValue / 100)

  def buildTab(folder: TabFolder, wrapTab: TabWrapper, node: NodeSeq): Unit = {

    def buildGrid(localGroup: Composite, node: NodeSeq, maxWidth: Int, maxHeight: Int): Unit = {
      (node \ "item").foreach { item =>
        val composite = new Composite(localGroup, SWT.NONE)
        wrapTab.addComposite((item \ "@name").text, composite)
        val coords = Tuple2[Int, Int](toNewMetric((item \ "@width").text.toInt, maxWidth), toNewMetric((item \ "@height").text.toInt, maxHeight))
        val color = Tuple3[Int, Int, Int](rand.nextInt(255), rand.nextInt(255), rand.nextInt(255))
        composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, coords._1, coords._2))
        (item \ "grid").text match {
          case "" =>
            composite.setLayout(fill)            
            val label = new Label(composite, SWT.NONE)
            label.setAlignment(SWT.CENTER)
            label.setText((item \ "@name").text + "\nWidth - " + (item \ "@width").text + "\nHeight - " + (item \ "@height").text)
            label.setBackground(new Color(localGroup.getDisplay, color._1, color._2, color._3))            
          case _ =>
            composite.setLayout(new GridLayout(coords._1, true))
            composite.setBackground(new Color(localGroup.getDisplay, liitleDarkness(color._1), liitleDarkness(color._2), liitleDarkness(color._2)))
            buildGrid(composite, (item \ "grid"), coords._1, coords._2)
        }
      }
    }

    val localGroup = new Composite(folder, SWT.NONE)
    localGroup setLayout (new GridLayout(AREA_MAX_SIZE, true))
    buildGrid(localGroup, node, AREA_MAX_SIZE, AREA_MAX_SIZE)
    wrapTab.tab.setControl(localGroup)
  }

}